package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.FindsDepartsChildrenUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 部门表 前端控制器
 * <p>
 * 
 * @Author: Steve @Since： 2019-01-22
 */
@RestController
@RequestMapping("/b/sysdepart/sysDepart")
@Slf4j
public class SysDepartController {

	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;

	/**
	 * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	 * @return
	 */
	@AutoLog(value = "用户人员查询")
	@ApiOperation(value="人员管理-树查询", notes="人员管理-树查询")
	@RequestMapping(value = "/queryUserTreeList", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> queryUserTreeList(@RequestParam(name = "menuPath",required = false) String menuPath){
		Result<List<SysDepartTreeModel>> result = new Result<>();
		try {
			List<SysDepartTreeModel> list = new ArrayList<>();
			if (StringUtils.isNotBlank(menuPath)){
				//根据权限加载
				List<SysDepart> departTreeList = new ArrayList<SysDepart>();
				List<SysDepart> departTree = sysUserRoleService.queryDepartTreeList(menuPath, SsoUtil.getLoginUser().getId(),null);
				if(departTree.size() >0){
					departTreeList.addAll(departTree);
					for (SysDepart depart:departTree){
						if(depart != null && depart.getType().equals("department")){
							List<SysDepart> userTreeList = sysUserService.getUserByDepardId(depart.getId());
							if(userTreeList.size() > 0){
								departTreeList.addAll(userTreeList);
							}
						}
					}
				}
				list = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(departTreeList);
			}
			result.setResult(list);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}
	/**
	 * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	 * @return
	 */
	@AutoLog(value = "部门查询")
	@ApiOperation(value="部门管理-树查询", notes="部门管理-树查询")
	@RequestMapping(value = "/queryDepartTreeLists", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> queryDepartTreeList(){
		Result<List<SysDepartTreeModel>> result = new Result<>();
		try {
			List<SysDepartTreeModel> list =sysDepartService.queryDepartTreeList();
			result.setResult(list);
			result.setSuccess(true);
		}catch (Exception e){
			log.error(e.getMessage(),e);
		}
		return  result;
	}

	/**
	 * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	 *
	 * @return
	 */
	@RequestMapping(value = "/selectMange", method = RequestMethod.GET)
	public Result<Integer> selectMange(@RequestParam(name="id",required=true) String id) {
		Result<Integer> result = new Result<>();
		try {
		   Integer selectCount =	sysDepartService.selectMange(id);
		   result.setResult(selectCount);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}

	/**
	 * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> queryTreeList() {
		Result<List<SysDepartTreeModel>> result = new Result<>();
		try {
			List<SysDepartTreeModel> list = sysDepartService.queryTreeList();
			result.setResult(list);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}

	/**
	 * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryCompanyTreeList", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> queryCompanyTreeList() {
		Result<List<SysDepartTreeModel>> result = new Result<>();
		try {
			List<SysDepartTreeModel> list = sysDepartService.queryCompanyTreeList();
			result.setResult(list);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}
	/**
	 * Oa模块树结构 查出所有部门,并以树结构数据格式响应给前端
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryDepartTreeListOa", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> queryDepartTreeListOa() {
		Result<List<SysDepartTreeModel>> result = new Result<>();
		try {
			List<SysDepartTreeModel> list = sysDepartService.queryDepartTreeListOa();
			result.setResult(list);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}
	/**
	 * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
	 * 
	 * @param sysDepart
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Result add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
//		Result<SysDepart> result = new Result<SysDepart>();
		try {
//			sysDepart.setCreateBy(username);
			List<SysDepart> childList = sysDepartService.findChildByParentIdAndName(sysDepart.getParentId(),null,sysDepart.getDepartName());
			if (childList.size() > 0){
				return Result.error("【" + sysDepart.getDepartName() + "】在系统中已存在,名称重复添加失败！");
			}
			StringBuilder departIds = new StringBuilder();
			if(sysDepart!=null && StringUtils.isNotBlank(sysDepart.getParentId())){
				SysDepart depart0 = sysDepartService.getById(sysDepart.getParentId());//当前部门上级部门ID
				if(depart0 != null){
					if(StringUtils.isNotBlank(depart0.getParentIds())) departIds.append(depart0.getParentIds());
					departIds.append(depart0.getId()+",");
				}
			}
			if(StringUtils.isNotBlank(departIds.toString())) sysDepart.setParentIds(departIds.toString());
			sysDepartService.saveDepartData(sysDepart);
			return Result.ok("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return Result.error("系统繁忙,操作失败");
		}
	}

	/**
	 * 编辑数据 编辑部门的部分数据,并保存到数据库
	 * 
	 * @param sysDepart
	 * @return
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.PUT)
	public Result edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
		List<SysDepart> childList = sysDepartService.findChildByParentIdAndName(sysDepart.getParentId(),sysDepart.getId(),sysDepart.getDepartName());
		if (childList.size() > 0){
			return Result.error("【" + sysDepart.getDepartName() + "】在系统中已存在,名称重复编辑失败！");
		}
		SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
		if (sysDepartEntity == null) {
			return Result.error("未找到对应实体");
		} else {
			return sysDepartService.updateDepartDataById(sysDepartEntity, sysDepart);
		}

	}
	
	 /**
     *   通过id删除
    * @param id
    * @return
    */
   @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
   public Result delete(@RequestParam(name="id",required=true) String id) {
       Result<SysDepart> result = new Result<SysDepart>();
       SysDepart sysDepart = sysDepartService.getById(id);
       if(sysDepart == null) {
           return result.error("未找到对应实体");
       }
	   if (sysDepart.getId().equals(sysDepart.getTenantId()) && CommonConstant.DEPART_PROPERTY_COMPANY.equals(sysDepart.getDepartProperty())){
		   return result.error("一级部门不可删除,操作失败!");
	   }
	   List<SysUser> sysUserList = sysUserService.findChildUserByDepartId(id);
	   if (sysUserList.size() > 0) return Result.error("当前部门下存在用户不可删除,请先删除或移走部门下的用户！");
	   boolean ok = sysDepartService.delete(id);
	   return Result.ok("删除成功!");
   }


	/**
	 * 批量删除 根据前端请求的多个ID,对数据库执行删除相关部门数据的操作
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
	public Result<SysDepart> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {

		Result<SysDepart> result = new Result<SysDepart>();
		if (ids == null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		} else {
			this.sysDepartService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	/**
	 * 查询数据 添加或编辑页面对该方法发起请求,以树结构形式加载所有部门的名称,方便用户的操作
	 * 
	 * @return
	 */
	@RequestMapping(value = "/queryIdTree", method = RequestMethod.GET)
	public Result<List<DepartIdModel>> queryIdTree() {
		Result<List<DepartIdModel>> result = new Result<List<DepartIdModel>>();
		List<DepartIdModel> idList;
		try {
			idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
			if (idList != null && idList.size() > 0) {
				result.setResult(idList);
				result.setSuccess(true);
			} else {
				sysDepartService.queryTreeList();
				idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
				result.setResult(idList);
				result.setSuccess(true);
			}
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.setSuccess(false);
			return result;
		}
	}

	/**
	 * @功能：根据id 批量查询
	 * @param departIds
	 * @return
	 */
	@RequestMapping(value = "/queryDepartByIds", method = RequestMethod.GET)
	public Result<Collection<SysDepart>> queryDepartByIds(@RequestParam String departIds) {
		Collection<String> idList = Arrays.asList( departIds.split(","));
		Collection<SysDepart> userRole = sysDepartService.listByIds(idList);
		return Result.ok(userRole);
	}

	 
	/**
	 * <p>
	 * 部门搜索功能方法,根据关键字模糊搜索相关部门
	 * </p>
	 * 
	 * @param keyWord
	 * @return
	 */
	@RequestMapping(value = "/searchBy", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> searchBy(@RequestParam(name = "keyWord", required = true) String keyWord) {
		Result<List<SysDepartTreeModel>> result = new Result<List<SysDepartTreeModel>>();
		try {
			List<SysDepartTreeModel> treeList = this.sysDepartService.searhBy(keyWord);
			if (treeList.size() == 0 || treeList == null) {
				throw new Exception();
			}
			result.setSuccess(true);
			result.setResult(treeList);
			return result;
		} catch (Exception e) {
			e.fillInStackTrace();
			result.setSuccess(false);
			result.setMessage("查询失败或没有您想要的任何数据!");
			return result;
		}
	}

	/**
	 * <p>
	 * 部门搜索功能方法,根据关键字模糊搜索相关部门
	 * </p>
	 *
	 * @param keyWord
	 * @return
	 */
	@RequestMapping(value = "/searchCompanyBy", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> searchCompanyBy(@RequestParam(name = "keyWord", required = true) String keyWord) {
		Result<List<SysDepartTreeModel>> result = new Result<List<SysDepartTreeModel>>();
		try {
			List<SysDepartTreeModel> treeList = this.sysDepartService.searhCompanyBy(keyWord);
			if (treeList.size() == 0 || treeList == null) {
				throw new Exception();
			}
			result.setSuccess(true);
			result.setResult(treeList);
			return result;
		} catch (Exception e) {
			e.fillInStackTrace();
			result.setSuccess(false);
			result.setMessage("暂无数据!");
			return result;
		}
	}

	@RequestMapping(value = "/querySubTreeByParentId", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> querySubTreeByParentId(@RequestParam(name = "treeType") String treeType,
																   @RequestParam(name = "parentId") String parentId,
																   @RequestParam(name = "tenantId",required = false) String tenantId,
																   @RequestParam(name = "targetType" ,required = false) String targetType) {
		if (StringUtils.isBlank(tenantId)){
			tenantId = SsoUtil.getLoginUser().getTenantId();
		}
		SysDepart sysDepart = new SysDepart();
		sysDepart.setParentId(parentId);
		sysDepart.setTenantId(tenantId);
		if (CommonConstant.DEPART_PROPERTY_CHANNEL.equals(treeType) || CommonConstant.DEPART_PROPERTY_OFFICE.equals(treeType) || CommonConstant.DEPART_PROPERTY_COMPANY.equals(treeType)){
			List<SysDepart> departList = sysDepartService.querySubTreeByParentId(sysDepart);
			List<SysDepartTreeModel> treeModelList = new ArrayList<>();
			departList.forEach(temp->{
				SysDepartTreeModel model = new SysDepartTreeModel(temp);
				model.setType(temp.getDepartProperty());
				treeModelList.add(model);
			});
			return Result.ok(treeModelList);
		}else if (CommonConstant.DEPART_PROPERTY_DEPARTMENT.equals(treeType)){
			return Result.ok(null);
		}

		return Result.ok();
	}



	/**
     * 导出excel
     *
     * @param request
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysDepart sysDepart,HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<SysDepart> queryWrapper = QueryGenerator.initQueryWrapper(sysDepart, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SysDepart> pageList = sysDepartService.list(queryWrapper);
        //按字典排序
        Collections.sort(pageList, new Comparator<SysDepart>() {
            @Override
			public int compare(SysDepart arg0, SysDepart arg1) {
            	return arg0.getOrgCode().compareTo(arg1.getOrgCode());
            }
        });
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "部门列表");
        mv.addObject(NormalExcelConstants.CLASS, SysDepart.class);
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("部门列表数据", "导出人:"+user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
            	// orgCode编码长度
            	int codeLength = 3;
                List<SysDepart> listSysDeparts = ExcelImportUtil.importExcel(file.getInputStream(), SysDepart.class, params);
                //按长度排序
                Collections.sort(listSysDeparts, new Comparator<SysDepart>() {
                    @Override
					public int compare(SysDepart arg0, SysDepart arg1) {
                    	return arg0.getOrgCode().length() - arg1.getOrgCode().length();
                    }
                });
                for (SysDepart sysDepart : listSysDeparts) {
                	String orgCode = sysDepart.getOrgCode();
                	if(orgCode.length() > codeLength) {
                		String parentCode = orgCode.substring(0, orgCode.length()-codeLength);
                		QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<SysDepart>();
                		queryWrapper.eq("org_code", parentCode);
                		try {
                		SysDepart parentDept = sysDepartService.getOne(queryWrapper);
							if(null != parentDept) {
								sysDepart.setParentId(parentDept.getId());
							} else {
								sysDepart.setParentId("");
							}
                		}catch (Exception e) {
                			//没有查找到parentDept
                		}
                	}else{
                		sysDepart.setParentId("");
					}
                    sysDepartService.save(sysDepart);
                }
                return Result.ok("文件导入成功！数据行数：" + listSysDeparts.size());
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                return Result.error("文件导入失败:"+e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }
}
